﻿#ifndef __CANVAS_H__
#define __CANVAS_H__

#include <QWidget>
#include <QEvent>
#include <QScrollArea>
#include <QList>
#include <QMouseEvent>
#include <QMetaObject>
#include <QMetaEnum>

#include "popmenu.h"
#include "shape/rhomboidshape.h"
#include "paint/borderpainter.h"
#include "paint/shapepainter.h"

class Canvas;
class ShapeManager;
enum class GirdPosition;
enum class SelectOperate
{
	//选择
	Select,
	//移动
	Move,
	//链接
	Connect,
	//伸缩
	Stretch
};


//图形管理者：它用于处理图形的状态
class ShapeManager : public QObject
{
	friend class Canvas;
private:
	Canvas* canvas;
	//管理悬停时的图形
	Shape* detect_shape;
	//管理链接时的图形
	Shape* linked_shape;
	//管理创造时的图形
	Shape* create_shape;
	//管理已链接的图形
	QList<ShapeLink*> linked_group;
	//管理被选中的图形
	QList<Shape*> select_shape;
	//管理已创建的图形
	QList<Shape*> entire_shape;
	//管理是否选择状态
	SelectOperate select_state;
	//管理鼠标起点终点
	QPoint cursor_begin;
	QPoint cursor_moved;
	QPoint cursor_final;
	//管理绘制的事件流
	QList<PainterType> paint_stream;
	//管理鼠标是否按下
	bool finish_press;
	//管理链接是否创建
	bool linked_creat;
	//管理伸缩时的方向
	GirdPosition position;

	//绘制预处理
	void beforePaint();
	//绘制事件流（需要更新绘制的数据时调用第一个接口，否则调用第二个接口）
	void createPaint(PainterType paint, const QPoint& start_point, const QPoint& final_point);
	void createPaint(PainterType paint);
	//绘制后处理
	void finishPaint();
public:
	enum class CreateMode
	{
		Save,
		Move,
		Edit
	};
	explicit ShapeManager(Canvas* parent = nullptr);
	//记录鼠标起点坐标并开启初始点击事件流
	void recordBegin(const QPoint& point);
	//记录鼠标移动坐标并开启鼠标移动事件流
	void recordMoved(const QPoint& point);
	//记录鼠标终点坐标并开启结束点击事件流
	void recordFinal(const QPoint& point);

	void recordShape(Shape* shape, CreateMode mode, const QPoint& point = QPoint());

	Shape* detectShape() const;
	Shape* createShape() const;
	const QList<Shape*>& selectShape() const;
	const QList<Shape*>& entireShape() const;
	const QList<ShapeLink*>& linkedGroup() const;
};

class Canvas : public QWidget
{
	Q_OBJECT
	Q_ENUM(PainterType)
	friend class ShapeManager;
private:
	//图形管理者
	ShapeManager* shape_manager;
	//绘制管理者
	QMap<PainterType, Painter*> paint_manager;
	//菜单管理者
	PopMenu* popup_manager;
public:
	explicit Canvas(QWidget* parent = nullptr);
	ShapeManager* getShapeManager() const;
protected:
	void mousePressEvent(QMouseEvent* event) override;
	void mouseMoveEvent(QMouseEvent* event) override;
	void mouseReleaseEvent(QMouseEvent* event) override;
	void paintEvent(QPaintEvent* event) override;
};

#endif // !__CANVAS_H__
